//微信授权调取js

const authorizer = require('../common/authorizer');
const $get_api = require('../common/api').HTTP;
const setInfo = require('../const').SET_INFO;
const util = require('../utils/util'); //引用工具
var post_data = {
    code:"",
    userinfo:"",
    iv:"",
    encryptedData:""
};
/**
 * @param {type} 小程序配置
 * 小程序授权登录配置 1. getUserProfile :获取所有详细信息  2. 空则获取部分信息 3. getPhoneNumber 手机号授权
 * 调用页面wxss：<van-button open-type="" bindtap="getUserProfile" >按钮</van-button>
 * 调用方法：在调用页面js
 *  getUserProfile: function (options) {
        wx_auth.authApply(options,app.useConst.LOGO_CONFIG.WX_LOGIN_TYPE)
    },
    手机号授权：
 *  wxss:<button open-type=”getPhoneNumber” bindgetphonenumber=”getPhoneNumber”></button>

    wx_avatarUrl_hidden 进入页面是否显示更新头像昵称，0是不显示， 1是显示

    obj 拼接传参对象 除jump_page是跳转指定页面 其余是拼接参数
 */
function authApply(e,page,type = '',obj = {}, wx_avatarUrl_hidden = 1) {
    if(type == "getUserProfile"){
      wx.getUserProfile({
          desc: '用于完善会员资料', 
          success:(res1)=>{
            wx.login({
              success: res2 => {
                // console.log("用户的code:" + res2.code);
                // console.log("用户的code:" + res1.userInfo);
                post_data.code = res2.code;
                post_data.userinfo = JSON.stringify(res1.userInfo);
                // console.log(post_data.userinfo);
                $get_api.wxLogin(post_data).then((result) => {
                    console.log(result);
                    let data = result.data.data;
                    wx.setStorageSync('token',result.data.data.token)
                    wx.setStorageSync('userInfo',JSON.stringify(result.data.data))
                    
                    if(data.is_update == 1 && wx_avatarUrl_hidden == 1 ){
                        console.log('更新头像和昵称');
                        wx.navigateTo({
                            url: '../wx_avatarUrl/wx_avatarUrl',
                        });
                    }
                    else{
                      if(setInfo.tapbarList.indexOf(util.get_url()) > -1 && obj == {}){
                        wx.reLaunch({
                            url: '/' + util.get_url(),
                        });
                    }else{
                      if( obj == {} ){
                        wx.navigateTo({
                          url: '/' + util.get_url(),
                        });
                      }else if(obj.jump_page != ""){
                        let jump_page = obj.jump_page;
                         // 字符串含有字符'c'
                        if (jump_page.includes('apply_member_join') && data.user_type == 1) {
                          //如果已经是会员并且申请注册过了，第二次进入再次申请入会 跳回首页
                         wx.switchTab({
                           url: '/pages/index/index',
                         })
                      }else{
                        wx.navigateTo({
                          url: jump_page,
                        });
                      }
                      }else if(Object.keys(obj).length > 1 && obj.jump_page != ""){

                        let jump_page = obj.jump_page;
                        obj.defineProperty(obj,"jump_page")
                        if (jump_page.includes('apply_member_join') && data.user_type == 1) {
                          //如果已经是会员并且申请注册过了，第二次进入再次申请入会 跳回首页
                         wx.switchTab({
                           url: '/pages/index/index',
                         })

                      }else{
                        wx.navigateTo({
                          url:  jump_page+ '?' + util.urlEncode(obj),
                        });
                      }

                      }else{
                        wx.navigateTo({
                          url: '/' + util.get_url() + '?' + util.urlEncode(obj),
                        });
                      }
                    }
                  
                        wx.showToast({
                            title: '登录成功',
                        })
                    }
                  }).catch((error) => {
                      console.log(error);
                  })
                  
                  }
             });
            
          },
          fail:(res)=>{
            console.log('用户点击取消！')
          }
      })     
    }
    if(type == "getPhoneNumber"){
      $get_api.phoneWxLogin(post_data).then((result) => {
          console.log(result);
        }).catch((error) => {
            console.log(error);
        })
    }
    if(type == ""){
        authorizer.authorize("scope.userInfo", function(res1) {
            wx.getUserInfo({
                success: function(res1){
                    wx.login({
                    success: res2 => {
                      // 获取到用户的 code 之后：res.code
                      post_data.code = res2.code;
                      post_data.userinfo = JSON.stringify(res1.userInfo);
                      console.log(post_data.userinfo);
                      $get_api.wxLogin(post_data).then((result) => {
                          console.log(result);
                          let data = result.data.data;
                          console.log(data,"datadatadata");
                          wx.setStorageSync('token',result.data.data.token)
                          wx.setStorageSync('userInfo',JSON.stringify(result.data.data))
                          if(data.is_update == 1 && wx_avatarUrl_hidden == 1){
                              console.log('更新头像和昵称');
                              //
                              if( obj == {} ){
                                  wx.navigateTo({
                                    url: '../wx_avatarUrl/wx_avatarUrl',
                                });
                              }else{
                                  wx.navigateTo({
                                      url: '../wx_avatarUrl/wx_avatarUrl?'+util.urlEncode(obj),
                                  });
                              }
                          }
                          else {
                            console.log(obj,"objobj",obj == {});
                            if(setInfo.tapbarList.indexOf(util.get_url()) > -1 && Object.keys(obj).length === 0){
                              wx.reLaunch({
                                  url: '/' + util.get_url(),
                              });
                          }else{
                            if( Object.keys(obj).length === 0 ){
                              wx.navigateTo({
                                url: '/' + util.get_url(),
                              });
                            }else if(obj.jump_page != "" && obj.jump_page != undefined){
                              let jump_page = obj.jump_page;
                               // 字符串含有字符'c'
                               console.log(data.user_type ,"data.user_type data.user_type data.user_type ");
                               console.log(jump_page.includes('apply_member_join') ,"11111");
                              if (jump_page.includes('apply_member_join') && data.user_type == 1) {
                                //如果已经是会员并且申请注册过了，第二次进入再次申请入会 跳回首页
                               wx.reLaunch({
                                 url: '/pages/index/index',
                               })
                            }else{
                              wx.navigateTo({
                                url: jump_page,
                              });
                            }
                            }else if(Object.keys(obj).length > 1 && obj.jump_page != "" && obj.jump_page != undefined){

                              let jump_page = obj.jump_page;
                              obj.defineProperty(obj,"jump_page")
                              
                              if (jump_page.includes('apply_member_join') && data.user_type == 1) {
                                //如果已经是会员并且申请注册过了，第二次进入再次申请入会 跳回首页
                                wx.reLaunch({
                                  url: '/pages/index/index',
                                })

                            }else{
                              wx.navigateTo({
                                url:  jump_page+ '?' + util.urlEncode(obj),
                              });
                            }

                            }else{
                              wx.navigateTo({
                                url: '/' + util.get_url() + '?' + util.urlEncode(obj),
                              });
                            }
                          }
                        }
                          wx.showToast({
                              title: '登录成功',
                          })
                      }).catch((error) => {
                          console.log(error);
                      })
                  }
                  });
        
            }});
            }, function(err) {
                console.log('userInfoback', err);
            }, function(err) {
                console.log('deniedBack', err);
            });
    }
}
    
/**
 * 
 * @param {验证登录} checkToken(is_post_checkout) 
 * 调用方法 1是没有请求的时候传 有请求的地方需要验证token则传0
 * 调取遮罩层的方法 <view class="aa" bingtap="getUserProfile" hidden="{{checkToken == false]}}"></view>
 * checkToken(1) 有token隐藏授权登录按钮;
 */
function checkToken(is_post_checkout = 0){
    var Token = wx.getStorageSync('token')
    if(Token == '' || Token == null){
        return false
     }
     if(is_post_checkout == 1){
        $get_api.isLogin(Token).then((result) => {
            // console.log(result,"result1321313");
            wx.setStorageSync('userInfo',JSON.stringify(result.data.data))
        }).catch((error) => {
          console.log(error);
        })
     }
     return true
}



module.exports = {
    authApply: authApply,
    post_data:post_data,
    checkToken:checkToken,
}


